package com.qk.management.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qk.code.ParamEnum;
import com.qk.constant.BusinessConstant;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessPoolDTO;
import com.qk.dto.business.BusinessTrackDTO;
import com.qk.entity.*;
import com.qk.exception.BusinessException;
import com.qk.management.annotation.BusinessStateMachineTransition;
import com.qk.management.annotation.LogAnno;
import com.qk.management.config.UserThreadLocal;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.service.BusinessService;
import com.qk.management.statemachine.event.BusinessEvent;
import com.qk.result.PageResult;
import com.qk.vo.business.BusinessPoolVO;
import com.qk.vo.business.BusinessQueryVO;
import com.qk.vo.business.BusinessTrackRecordVO;
import com.qk.vo.business.BusinessVO;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Author:zhengbowen
 * @Date: 2025/10/13 11:48
 * @Description: 商机逻辑
 */
@Service
@RequiredArgsConstructor
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {

    private final BusinessTrackRecordMapper businessTrackRecordMapper;
    private final CustomerMapper customerMapper;

    @Override
    @LogAnno
    @BusinessStateMachineTransition(machineId = "#businessId", event = BusinessEvent.ASSIGN, queryFromDatabase = true)
    public void updateBusinessById(Integer businessId, Integer userId) {
        Business business = Business.builder()
                .id(businessId)
                .userId(userId)
                .updateTime(LocalDateTime.now())
                .build();
        this.baseMapper.updateById(business);
    }

    @Override
    public void insert(Business business) {
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        business.setStatus(BusinessConstant.BUSINESS_STATUS_WAIT);
        this.baseMapper.insert(business);
    }

    @Override
    @LogAnno
    @Transactional(rollbackFor = Exception.class)
    @BusinessStateMachineTransition(machineId = "#id", event = BusinessEvent.RECYCLE, queryFromDatabase = true)
    public void backPublicSea(Integer id) {
        if (Objects.isNull(id)) {
            throw new BusinessException(ParamEnum.PARAM_ERROR);
        }
        Business business = Business.builder()
                .id(id)
                .updateTime(LocalDateTime.now())
                .build();
        this.baseMapper.updateById(business);
    }


    @Override
    @LogAnno
    @Transactional(rollbackFor = Exception.class)
    @BusinessStateMachineTransition(machineId = "#id", event = BusinessEvent.CONVERT_TO_CUSTOMER, queryFromDatabase = true)
    public void convertToCustomer(Integer id) {
        Business business = this.baseMapper.selectById(id);
        if (Objects.isNull(business)) {
            throw new BusinessException(ParamEnum.PARAM_ERROR);
        }
        Customer customer = new Customer();
        BeanUtils.copyProperties(business, customer);
        customer.setId(null);
        customer.setBusinessId(id);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        this.baseMapper.deleteById(id);
        customerMapper.insert(customer);
    }

    @Override
    public BusinessVO getBusinessById(Integer id) {
        if (Objects.isNull(id)) {
            throw new BusinessException(ParamEnum.PARAM_ERROR);
        }
        Business business = this.baseMapper.selectById(id);
        BusinessVO businessVO = new BusinessVO();
        BeanUtils.copyProperties(business, businessVO);
        List<BusinessTrackRecordVO> businessTrackRecordListVO = businessTrackRecordMapper.selectVOByBusinessId(id);
        businessVO.setTrackRecords(businessTrackRecordListVO);
        return businessVO;
    }

    @Override
    @LogAnno
    @Transactional(rollbackFor = Exception.class)
    @BusinessStateMachineTransition(machineId = "#businessTrackDTO.id", event = BusinessEvent.FOLLOW_UP, queryFromDatabase = true)
    public void trackBusiness(@NotNull BusinessTrackDTO businessTrackDTO) {
        Integer currentId = UserThreadLocal.getUser().getId();
        businessTrackDTO.setUpdateTime(LocalDateTime.now());
        Business business = new Business();
        BeanUtils.copyProperties(businessTrackDTO, business);
        this.baseMapper.updateById(business);
        BusinessTrackRecord businessTrackRecord = BusinessTrackRecord.builder()
                .businessId(businessTrackDTO.getId())
                .userId(currentId)
                .trackStatus(businessTrackDTO.getTrackStatus())
                .keyItems(String.join(",", businessTrackDTO.getKeyItems() != null ? businessTrackDTO.getKeyItems() : new String[0]))
                .nextTime(businessTrackDTO.getNextTime())
                .record(businessTrackDTO.getRecord())
                .createTime(LocalDateTime.now())
                .build();
        businessTrackRecordMapper.insert(businessTrackRecord);
    }

    @Override
    public PageResult<BusinessPoolVO> selectBusinessPool(BusinessPoolDTO businessPoolDTO) {

        PageHelper.startPage(businessPoolDTO.getPage(), businessPoolDTO.getPageSize());
        List<BusinessPoolVO> businessVOList = this.baseMapper.selectBusinessPoolByPage(businessPoolDTO);
        PageInfo<BusinessPoolVO> pageInfo = new PageInfo<>(businessVOList);
        return PageResult.<BusinessPoolVO>builder()
                .rows(pageInfo.getList())
                .total(pageInfo.getTotal())
                .build();
    }


    @Override
    public PageResult<BusinessQueryVO> selectBusinessByPage(BusinessDTO businessDTO) {
        PageHelper.startPage(businessDTO.getPage(), businessDTO.getPageSize());
        List<BusinessQueryVO> businessVOList = this.baseMapper.selectBusinessByPage(businessDTO);
        PageInfo<BusinessQueryVO> pageInfo = new PageInfo<>(businessVOList);
        return PageResult.<BusinessQueryVO>builder()
                .total(pageInfo.getTotal())
                .rows(pageInfo.getList())
                .build();
    }
}
